package com.sljy.hzk.util;

import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import java.util.List;

public class MyReceiver extends BroadcastReceiver
{
    public static final String MY_ACTION = "COM_LDM_SRATR_SERVER";

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        //if (intent.getAction().equals(MY_ACTION)) {
            //判断要启动的Service是否正在运行
            boolean isRunning = serviceRunState(context,
                    "com.sljy.hzk.util.NotificationService");
            if (!isRunning) {//Service没有运行,则启动服务
                Intent in = new Intent(context, NotificationService.class);
                if (android.os.Build.VERSION.SDK_INT >= 12) {
                    // 3.1以后设置Intent.FLAG_INCLUDE_STOPPED_PACKAGES
                    in.setFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
                }
                context.startService(in);
            }
       // }
    }
    /**
     * 判断指定Service运行的状态
     * @param context
     * @param className
     * @return
     */
    public static boolean serviceRunState(Context context, String className) {
        boolean isRun = false;
        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> serviceList = activityManager
                .getRunningServices(30);
        if (!(serviceList.size() > 0)) {
            return false;
        }
        for (int i = 0; i < serviceList.size(); i++) {
            if (serviceList.get(i).service.getClassName().equals(className)) {
                isRun = true;
                break;
            }
        }
        return isRun;
    }
}
